package com.chuangyang.fixboxmaster.ui.fragment.orderprice;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.ChangePriceEvent;
import com.chuangyang.fixboxmaster.bean.CostItem;
import com.chuangyang.fixboxmaster.bean.CostItemInfo;
import com.chuangyang.fixboxmaster.bean.OrderDetail;
import com.chuangyang.fixboxmaster.bean.OrderPriceItem;
import com.chuangyang.fixboxmaster.bean.PriceItem;
import com.chuangyang.fixboxmaster.bean.VerifyCodeEvent;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.MainActivity;
import com.chuangyang.fixboxmaster.ui.ModuleActivity;
import com.chuangyang.fixboxmaster.ui.adapter.CostDetailAdapter;
import com.chuangyang.fixboxmaster.ui.adapter.PriceDetailAdapter;
import com.chuangyang.fixboxmaster.ui.fragment.BaseFragment;
import com.chuangyang.fixboxmaster.ui.widgets.PinnedSectionListView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2015/6/3.
 */
public class CostDetailFragment extends BaseFragment implements View.OnClickListener {


    private View mContentView;

    private PinnedSectionListView mCostDetailLV;
    private TextView mTotalCostView;
    private TextView mOKBtnView;
    private CostDetailAdapter mAdapter;
    private String mOrderID;
    private String mTransactionId;
    private String mSpecificationId;
    private String mProductDate;
    private String mBrandId;
    private ArrayList<CostItem> mCostItems;
    private ArrayList<OrderPriceItem> mOrderPriceItems;
    private ArrayList<PriceItem> mPriceItem = new ArrayList<>();
    private PriceDetailAdapter mDetailAdapter;
    private boolean isChangePriceAlready=false;


    public static CostDetailFragment newInstance() {
        return new CostDetailFragment();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_cost_detail, container, false);
        initView();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        loadData();
        initData();
        EventBus.getDefault().registerSticky(this);
    }


     public void onEvent(ChangePriceEvent event) {
         if(event.isReprice==1){
             isChangePriceAlready=true;
         }
    }

    private void initView(){
        mCostDetailLV = (PinnedSectionListView)mContentView.findViewById(R.id.cost_detail_listview);
        mTotalCostView = (TextView)mContentView.findViewById(R.id.total_cost);
        mTotalCostView.setOnClickListener(this);
        mOKBtnView = (TextView)mContentView.findViewById(R.id.btn_ok);
        mOKBtnView.setOnClickListener(this);
    }

    private void loadData(){
        mCostItems = (ArrayList<CostItem>)getArguments().getSerializable(ModuleActivity.COST_ITEM);
        mOrderID = getArguments().getString(ModuleActivity.ORDER_ID);
        mTransactionId = getArguments().getString(ModuleActivity.TRANSCATION_ID);
        mSpecificationId = getArguments().getString(ModuleActivity.SPECIFICATION_ID);
        mProductDate = getArguments().getString(ModuleActivity.PRODUCT_DATE);
        mBrandId = getArguments().getString(ModuleActivity.BRAND_ID);
        /*if (mCostItems != null)
            mAdapter = new CostDetailAdapter(getActivity(),mCostItems);
        else
        {
            if (Integer.parseInt(mTransactionId) == CompleteApplianceInfoActivity.TRANSCATION_ID_CLEAN)
            {
                HashMap<String, String> param = new HashMap<>();
                param.put("transactionId", mTransactionId);
                param.put("specificationId", mSpecificationId);
                addRequest(new GsonRequest<>(FixBoxApi.GET_CLEAN_SERVICE_FREE, param, CostItemInfo.class, cleanFreeFeesponseListener));
            }
        }*/ //2.0 版注释
        mOrderPriceItems = (ArrayList<OrderPriceItem>)getArguments().getSerializable(ModuleActivity.ORDER_PRICE_ITEM);
        generatePriceItems();
    }

    private Response.Listener<CostItemInfo> cleanFreeFeesponseListener = new Response.Listener<CostItemInfo>() {
        @Override
        public void onResponse(CostItemInfo response) {

            if (response.result != null)
            {
                mCostItems = new ArrayList<>();
                mCostItems.addAll(Arrays.asList(response.result));
                mAdapter = new CostDetailAdapter(getActivity(),mCostItems);
               initData();
            }
        }
    };

    private void initData(){
        /*if (mCostItems == null)
            return;
        mCostDetailLV.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        setTotalPrice();
        showResult();*/ //2.0 版注释
        if (mOrderPriceItems == null)
            return;
        // 初始化费用列表
       /* for (OrderPriceItem item : mOrderPriceItems)
        {
            View mFooterView = LayoutInflater.from(getActivity()).inflate(R.layout.order_price_detail_item, null);
            TextView title = (TextView)mFooterView.findViewById(R.id.title);
            title.setText(""+item.title+item.index);
            ListView listView = (ListView)mFooterView.findViewById(R.id.detail_list);
            ArrayList<CostItem> costItems = new ArrayList<>();
            costItems.addAll(Arrays.asList(item.costitem));
            CostDetailAdapter adapter = new CostDetailAdapter(getActivity(),costItems);
            listView.setAdapter(adapter);
            mCostDetailLV.addView(mFooterView);
            //mCostDetailLV.addFooterView(mFooterView, null, false);
        }*/
        mDetailAdapter = new PriceDetailAdapter(mPriceItem);
        mCostDetailLV.setAdapter(mDetailAdapter);
        setTotalPrice();
        showResult();
    }

    private void generatePriceItems(){

        for (OrderPriceItem item:mOrderPriceItems)
        {
            PriceItem sectionItem = new PriceItem();

            // section
            sectionItem.type = PriceItem.SECTION;
            sectionItem.sectionTitle = item.title;
            mPriceItem.add(sectionItem);

            // item
            for (CostItem costItem:item.costitem)
            {
                PriceItem priceItem = new PriceItem();
                priceItem.type = PriceItem.ITEM;
                priceItem.costItem = costItem;
                mPriceItem.add(priceItem);
            }
        }
    }

    private String getCostItemJson(){

        Gson gson = new Gson();
        String json = gson.toJson(mOrderPriceItems);

        return json;
    }

    private void submit(){
        HashMap<String, String> param = new HashMap<>();
        param.put("id", mOrderID);
        param.put("costItem", getCostItemJson());
        if(isChangePriceAlready){
            param.put("isReprice","1");
        }
        //param.put("specificationId", mSpecificationId);
        //param.put("brandId", mBrandId);
        if (mProductDate != null && !mProductDate.equals("") && !mProductDate.equals("null"))
        {
            Log.e("","");
            param.put("productDate", mProductDate);
        }
        addRequest(new GsonRequest<>(FixBoxApi.ORDER_FIX_FINISH, param, OrderDetail.class, responseListener));
    }

    private Response.Listener<OrderDetail> responseListener = new Response.Listener<OrderDetail>() {
        @Override
        public void onResponse(OrderDetail response) {
            Toast.makeText(getActivity(), "定价成功!", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getActivity(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
            Bundle bundle = new Bundle();
            bundle.putString("action","price_success");
            bundle.putString(ModuleActivity.ORDER_ID, mOrderID);
            intent.putExtras(bundle);
            startActivity(intent);
            //showResult();
        }
    };

    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.total_cost:
                //getActivity().finish();
                break;
            case R.id.btn_ok:
                submit();
                break;
            default:
                break;
        }
    }
    private void setTotalPrice(){

        int totalPrice = 0;

        for (OrderPriceItem item : mOrderPriceItems)
        {
            for (CostItem costItem:item.costitem)
            {
                totalPrice += costItem.num*costItem.price;
            }
        }
        mTotalCostView.setText("合计: ￥" +totalPrice);
    }

   /* @Override
    public ListView getListView() {
        return mCostDetailLV;
    }*/ // 2.0版注释
}
